<template>
	<view class="container">
		<!-- 音频信息 -->
		<view class="audio-info">
			<view class="audio-title">配音文件</view>
			<view class="audio-desc">点击下方按钮导出配音文件</view>
		</view>
		
		<!-- 音频播放器 -->
		<view class="audio-player">
			<view class="player-controls">
				<button class="control-btn" @tap="handlePlay">
					{{ isPlaying ? '暂停' : '播放' }}
				</button>
				<button class="control-btn" @tap="handleStop">停止</button>
			</view>
			<view class="player-progress">
				<text class="time">{{ formatTime(currentTime) }}</text>
				<slider 
					:value="sliderValue" 
					:max="100" 
					:disabled="!duration"
					@changing="handleSliderChanging"
					@change="handleSliderChange"
					activeColor="#35ae91"
					backgroundColor="#f5f5f5"
					block-size="12"
				/>
				<text class="time">{{ formatTime(duration) }}</text>
			</view>
		</view>
		
		<!-- 导出选项 -->
		<view class="export-options">
			<view class="option-item">
				<text class="option-label">文件格式</text>
				<view class="option-value">
					<text class="selected">MP3</text>
				</view>
			</view>
			<!-- <view class="option-item">
				<text class="option-label">文件名称</text>
				<view class="option-value">
					<input 
						type="text" 
						v-model="fileName" 
						placeholder="请输入文件名称" 
						class="file-name-input"
					/>
				</view>
			</view> -->
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<!-- <button class="primary-btn" @tap="handleExport">导出配音</button> -->
			<button class="wechat-btn" @tap="handleExportToWechat">导出到微信</button>
		</view>
		
		<!-- 导出成功弹框 -->
		<view class="export-success-modal" v-if="showSuccessModal">
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">导出成功</text>
					<text class="close-btn" @tap="closeSuccessModal">×</text>
				</view>
				<view class="modal-body">
					<view class="path-info">
						<text class="path-label">保存路径：</text>
						<text class="path-value">{{ savePath }}</text>
					</view>
					<button class="copy-btn" @tap="copySavePath">复制路径</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { ttsState } from '@/services/tts'
import { onLoad } from '@dcloudio/uni-app'

const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const sliderValue = ref(0)
const isUserSlidingProgress = ref(false)
const fileName = ref('配音文件')
const currentAudioContext = ref(null)
const showSuccessModal = ref(false)
const savePath = ref('')

// 获取路由参数
const audioUrl = ref('')
onLoad((options) => {
	
	if (options?.url) {
		audioUrl.value = decodeURIComponent(options.url)
		// 自动开始播放
		playAudio(audioUrl.value)
	}
})

// 格式化时间
function formatTime(seconds) {
	seconds = Math.floor(seconds || 0)
	const minutes = Math.floor(seconds / 60)
	seconds = seconds % 60
	return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 播放音频
function playAudio(url) {
	try {
		// 如果已经在播放，先停止
		if (currentAudioContext.value) {
			stopAudio()
		}
		
		// 创建新的音频上下文
		currentAudioContext.value = uni.createInnerAudioContext()
		currentAudioContext.value.src = url
		currentAudioContext.value.autoplay = true
		
		// 监听播放状态
		currentAudioContext.value.onPlay(() => {
			console.log('开始播放')
			isPlaying.value = true
		})
		
		currentAudioContext.value.onPause(() => {
			console.log('暂停播放')
			isPlaying.value = false
		})
		
		currentAudioContext.value.onEnded(() => {
			console.log('播放结束')
			isPlaying.value = false
			currentTime.value = 0
			sliderValue.value = 0
		})
		
		// 监听播放进度
		currentAudioContext.value.onTimeUpdate(() => {
			console.log('时间更新:', currentAudioContext.value.currentTime, '总时长:', currentAudioContext.value.duration)
			
			if (!isUserSlidingProgress.value) {
				// 确保获取到有效的当前时间和总时长
				const current = currentAudioContext.value.currentTime || 0
				const total = currentAudioContext.value.duration || 0
				
				// 更新当前时间
				currentTime.value = current
				
				// 只有当总时长有效时才更新进度条
				if (total > 0) {
					// 计算百分比值
					const percentage = (current / total) * 100
					sliderValue.value = percentage
					
					// 如果总时长之前未设置，则在这里更新
					if (duration.value === 0 || duration.value !== total) {
						duration.value = total
						console.log('更新总时长:', total)
					}
				}
			}
		})
		
		// 监听音频加载完成
		currentAudioContext.value.onCanplay(() => {
			console.log('音频加载完成')
			setTimeout(() => {
				// 在某些平台上，需要延迟获取duration
				const audioDuration = currentAudioContext.value.duration
				console.log('音频总时长:', audioDuration)
				if (audioDuration && audioDuration > 0) {
					duration.value = audioDuration
				}
			}, 300)
		})
		
		currentAudioContext.value.onError((err) => {
			console.error('音频播放错误:', err)
			isPlaying.value = false
			uni.showToast({
				title: '播放失败，请重试',
				icon: 'none'
			})
		})
	} catch (error) {
		console.error('创建音频上下文失败:', error)
		uni.showToast({
			title: '播放失败，请重试',
			icon: 'none'
		})
	}
}

// 处理滑块拖动中
function handleSliderChanging(e) {
	isUserSlidingProgress.value = true
	const value = e.detail.value
	if (duration.value > 0) {
		currentTime.value = (value / 100) * duration.value
	}
}

// 处理滑块拖动结束
function handleSliderChange(e) {
	const value = e.detail.value
	console.log('滑块拖动结束，值:', value)
	
	if (currentAudioContext.value && duration.value > 0) {
		const targetTime = (value / 100) * duration.value
		console.log('跳转到:', targetTime, '秒, 总时长:', duration.value)
		
		// 确保目标时间在有效范围内
		if (targetTime >= 0 && targetTime <= duration.value) {
			currentAudioContext.value.seek(targetTime)
			currentTime.value = targetTime
		}
	}
	
	// 延迟重置拖动状态，避免跳动
	setTimeout(() => {
		isUserSlidingProgress.value = false
	}, 200)
}

// 停止播放
function stopAudio() {
	if (currentAudioContext.value) {
		currentAudioContext.value.stop()
		currentAudioContext.value.destroy()
		currentAudioContext.value = null
		isPlaying.value = false
		currentTime.value = 0
		sliderValue.value = 0
		duration.value = 0
	}
}

// 处理播放/暂停
function handlePlay() {
	if (!currentAudioContext.value) {
		if (audioUrl.value) {
			playAudio(audioUrl.value)
		}
		return
	}
	
	if (isPlaying.value) {
		currentAudioContext.value.pause()
	} else {
		currentAudioContext.value.play()
	}
}

// 处理停止
function handleStop() {
	stopAudio()
}

// 处理导出
async function handleExport() {
	try {
		if (!audioUrl.value) {
			throw new Error('没有可导出的音频')
		}
		
		uni.showLoading({
			title: '导出中...',
			mask: true
		})
		
		// 下载音频文件
		const downloadRes = await uni.downloadFile({
			url: audioUrl.value
		})
		
		if (downloadRes.statusCode !== 200) {
			throw new Error('下载失败')
		}
		
		// 保存文件
		await uni.saveFile({
			tempFilePath: downloadRes.tempFilePath
		})
		
		uni.hideLoading()
		uni.showToast({
			title: '导出成功',
			icon: 'success'
		})
		
		// 导出成功后显示弹框
		savePath.value = 'D:/Downloads/配音文件.mp3' // 这里替换为实际的保存路径
		showSuccessModal.value = true
	} catch (error) {
		uni.hideLoading()
		uni.showToast({
			title: error.message || '导出失败，请重试',
			icon: 'none'
		})
	}
}

// 复制保存路径
function copySavePath() {
	uni.setClipboardData({
		data: savePath.value,
		success: () => {
			uni.showToast({
				title: '路径已复制',
				icon: 'success'
			})
		}
	})
}

// 关闭成功弹框
function closeSuccessModal() {
	showSuccessModal.value = false
	// // 返回上一页 (暂时注释掉，因为用户可能需要复制路径)
	// uni.navigateBack()
}
async function saveFile(tempFilePath) {
    return new Promise((resolve, reject) => {
        wx.getFileSystemManager().saveFile({
            tempFilePath: tempFilePath,
            success: (res) => {
                resolve(res.savedFilePath);
            },
            fail: (err) => reject(err)
        });
    });
}
// 处理导出到微信
async function handleExportToWechat() {
	try {
		if (!audioUrl.value) {
			throw new Error('没有可导出的音频')
		}
		
		uni.showLoading({
			title: '准备分享...',
			mask: true
		})
		
		// 下载音频文件
		const downloadResult = await uni.downloadFile({
			url: audioUrl.value
		})
		
		if (downloadResult.statusCode !== 200) {
			throw new Error('音频下载失败')
		}
		
		// 不需要显式保存，分享接口可以直接使用临时路径
		const tempFilePath = downloadResult.tempFilePath
		const savedFilePath = await saveFile(tempFilePath)
		uni.hideLoading()
		// 使用系统分享
		wx.showModal({
			title: '提示',
			content: '是否转发文件',
			success: async(res) => {
				if (res.confirm) {
					// wx.shareFile({
					// 	filePath: savedFilePath,
					// 	success: (res) => {
					// 		console.log('文件分享成功');
					// 	},
					// 	fail: (err) => {
					// 		console.error('文件分享失败', err);
					// 	}
					// });
					// 下载完成后转发
					await wx.shareFileMessage({
						filePath: savedFilePath,
					})
				} else if (res.cancel) {
					console.log('用户取消分享');
				}
			}
		});
		
	} catch (error) {
		uni.hideLoading()
		uni.showToast({
			title: error.message || '导出失败，请重试',
			icon: 'none'
		})
	}
}

// 组件卸载时清理
onUnmounted(() => {
	if (currentAudioContext.value) {
		currentAudioContext.value.destroy()
	}
})
</script>

<style lang="scss">
.container {
	padding: 30rpx;
	padding-bottom: 180rpx;
	background: #f8f8f8;
	min-height: 100vh;
}

.audio-info {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	text-align: center;
	
	.audio-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.audio-desc {
		font-size: 28rpx;
		color: #666;
	}
}

.audio-player {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	
	.player-controls {
		display: flex;
		justify-content: center;
		gap: 30rpx;
		margin-bottom: 30rpx;
		
		.control-btn {
			width: 120rpx;
			height: 120rpx;
			border-radius: 60rpx;
			background: #35ae91;
			color: #fff;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			&:active {
				opacity: 0.9;
			}
		}
	}
	
	.player-progress {
		display: flex;
		align-items: center;
		
		.time {
			font-size: 24rpx;
			color: #999;
			width: 60rpx;
			text-align: center;
		}
		
		slider {
			flex: 1;
			margin: 0 20rpx;
		}
	}
}

.export-options {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	
	.option-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1px solid #f5f5f5;
		
		&:last-child {
			border-bottom: none;
		}
		
		.option-label {
			font-size: 28rpx;
			color: #333;
		}
		
		.option-value {
			.selected {
				font-size: 28rpx;
				color: #35ae91;
				font-weight: bold;
			}
			
			.file-name-input {
				width: 300rpx;
				height: 60rpx;
				border: 1px solid #e5e5e5;
				border-radius: 6rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
			}
		}
	}
}

.bottom-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	padding: 20rpx;
	background: #fff;
}

.primary-btn {
	width: 100%;
	background: #35ae91;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 20rpx 0;
	font-size: 30rpx;
}

.wechat-btn {
	width: 100%;
	background: #07c160;
	color: #fff;
	border: none;
	border-radius: 8rpx;
	padding: 20rpx 0;
	font-size: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&::before {
		content: '';
		display: inline-block;
		width: 40rpx;
		height: 40rpx;
		background: url('') no-repeat center/contain;
		margin-right: 10rpx;
	}
}

.export-success-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.modal-content {
		width: 80%;
		background: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		
		.modal-header {
			padding: 30rpx;
			text-align: center;
			position: relative;
			border-bottom: 1rpx solid #f5f5f5;
			
			.modal-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
			
			.close-btn {
				position: absolute;
				right: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				font-size: 40rpx;
				color: #999;
				padding: 10rpx;
			}
		}
		
		.modal-body {
			padding: 30rpx;
			
			.path-info {
				margin-bottom: 30rpx;
				
				.path-label {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 10rpx;
					display: block;
				}
				
				.path-value {
					font-size: 28rpx;
					color: #333;
					word-break: break-all;
					display: block;
					background: #f8f8f8;
					padding: 20rpx;
					border-radius: 8rpx;
				}
			}
			
			.copy-btn {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				background: #07c160;
				color: #fff;
				font-size: 28rpx;
				border-radius: 40rpx;
				border: none;
				
				&:active {
					opacity: 0.9;
				}
			}
		}
	}
}
</style> 